<template>
    <img :src="base64" />
</template>

<script setup lang="ts">
import { computed } from 'vue'

interface PropsType {
    width: number
    height: number
    bgcolor?: string
    color?: string
    text?: string
    font?: string
}
const props = withDefaults(defineProps<PropsType>(), {
    bgcolor: '#ccc',
    color: '#959595',
    text: undefined,
    font: 'Consolas'
})

const base64 = computed(() => {
    let text = props.text === undefined ? (props.width + 'x' + props.height) : props.text
    let canvas = window.document.createElement('canvas')
    canvas.width = props.width
    canvas.height = props.height
    let ctx = canvas.getContext('2d')!
    ctx.fillStyle = props.bgcolor
    ctx.fillRect(0, 0, props.width, props.height)
    ctx.fillStyle = props.color
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'
    let textHeight = Math.min(props.width, props.height) / 2
    ctx.font = textHeight + 'px ' + props.font
    if (text) {
        ctx.fillText(text, props.width / 2, props.height / 2)
    }
    let imageData = canvas.toDataURL()
    return imageData
})
</script>
